package com.cgg.stock.user.util;

import com.cgg.stock.common.pojo.User;
import com.google.code.kaptcha.Constants;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

public class UserContext {

    private static  final String USER_IN_SESSION = "loginUser";

    /**
     * 得到当前用户的session对象
     * @return
     */
    public static HttpSession getSession(){
        //Spring提供了RequestContextHolder类, 提供public static RequestAttributes getRequestAttributes()
        //RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //得到RequestAttributes对象 转换ServletRequestAttributes(子类)
        //ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
        //ServletRequestAttributes 得到Request,Response,Session对象
        //return servletRequestAttributes.getRequest().getSession();

        //点运算符 优先级高于()
        return ((ServletRequestAttributes)(RequestContextHolder.getRequestAttributes())).getRequest().getSession();
    }

    //获取Session中的验证码
    public static  String getVerifyCode(){
        return (String) getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
    }

    /**
     * 把登录的用户保存到Session
     */
    public static void setLoginUser(User user){
        getSession().setAttribute(USER_IN_SESSION,user);
    }

    /**
     * 从session获取登录用户
     * @return
     */
    public static User getLoginUser(){
        return (User) getSession().getAttribute(USER_IN_SESSION);
    }
}
